package com.cnb.telepathytalk.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.util.Log;

import com.cnb.telepathytalk.TelepathyTalkApplication;

public class VersionParser {
	private static final String TAG = "VersionParser";
	private static final String XML_URL = "http://telepathy.cnbridge.co.kr/xml/appVersion.cnb?type=android";

	public boolean parsingData(Context context) {
		String version = "";

		try {
			XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();

			HttpClient client = new DefaultHttpClient();

			client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

			HttpPost post = new HttpPost(XML_URL);

			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			if (response.getStatusLine().getStatusCode() != 200) {
				Log.e(TAG, "POST ERROR!!!");
			}

			parser.setInput(entity.getContent(), "UTF-8");

			int event = parser.next();

			while (event != XmlPullParser.END_DOCUMENT) {
				switch (event) {
				case XmlPullParser.START_TAG:
					if ("VERSION".equals(parser.getName())) {
						version = parser.nextText();
					}
					break;
				default:
					break;
				}
				event = parser.next();
			}
		} catch (Exception e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		}

		int versionNew;
		int versionOld;
		try {
			versionOld = TelepathyTalkApplication.appVersion;
			versionNew = Integer.parseInt(version);
		} catch (Exception e) {
			versionNew = 0;
			versionOld = 0;
		}

		if (versionNew > versionOld) {
			return true;
		} else {
			return false;
		}
	}
}